package com.zmzncs.shop.module.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zmzncs.shop.common.pojo.AuthorizeVO;
import com.zmzncs.shop.common.pojo.LoginUser;
import com.zmzncs.shop.common.util.*;
import com.zmzncs.shop.module.shop.mapper.ManagerShopMapper;
import com.zmzncs.shop.module.shop.pojo.managershop.ManagerShop;
import com.zmzncs.shop.module.shop.pojo.managershop.ManagerShopDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import com.zmzncs.shop.module.shop.pojo.shopmanager.*;
import com.zmzncs.shop.module.shop.mapper.ShopManagerMapper;
import com.zmzncs.shop.module.shop.service.ShopManagerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 高博文
 * @since 2021-05-25
 */
@Slf4j
@Service
public class ShopManagerServiceImpl extends ServiceImpl<ShopManagerMapper, ShopManager> implements ShopManagerService {

    //  验证码map
    private static Map<String, Map> verifyCodeMap = new HashMap();

    @Autowired
    HttpServletRequest request;
    @Autowired
    ShopManagerMapper shopManagerMapper;
    @Autowired
    ManagerShopMapper managerShopMapper;

    /**
    * 分页
    */
    @Override
    public IPage<ShopManagerDTO> page(ShopManagerSearchForm form){
        IPage<ShopManagerDTO> iPage = shopManagerMapper.list(form.getPage());

        return iPage;
    }

    /**
    * 添加
    */
    @Override
    @Transactional
    public void add(ShopManagerAddForm form){
        List<ShopManagerDTO> shopManagerDTOList = shopManagerMapper.getByMobilePhone(form.getTelephone());
        if(shopManagerDTOList.size() > 0){
            ExceptionUtil.businessException("手机号已存在");
        }

        //  添加商户
        ShopManager shopManager = new ShopManager();
        BeanUtils.copyProperties(form, shopManager);
        shopManager.setIsDeleted(0);
        shopManager.setPassword("000000");
        shopManager.setIsShopkeeper(0);
        shopManagerMapper.insert(shopManager);

        //  添加店铺
        ManagerShop managerShop = new ManagerShop();
        managerShop.setManagerId(shopManager.getId());
        managerShop.setShopId(form.getShopId());
        managerShop.setIsDeleted(0);
        managerShopMapper.insert(managerShop);
    }

    /**
    * 删除
    */
    @Override
    @Transactional
    public void delete(Long id){
        ShopManager shopManager = new ShopManager();
        shopManager.setId(id);
        shopManager.setIsDeleted(1);

        shopManagerMapper.updateById(shopManager);
    }

    /**
    * 修改
    */
    @Override
    @Transactional
    public void update(ShopManagerUpdateForm form){
        List<ShopManagerDTO> shopManagerDTOList = shopManagerMapper.getByMobilePhone(form.getTelephone());
        if(shopManagerDTOList.size() > 0 && !form.getId().equals(shopManagerDTOList.get(0).getId())){
            ExceptionUtil.businessException("手机号已存在");
        }

        ShopManager shopManager = new ShopManager();
        BeanUtils.copyProperties(form, shopManager);

        shopManagerMapper.updateById(shopManager);
    }

    /**
    * 详情
    */
    @Override
    public ShopManagerDTO getById(Long id){
        ShopManagerDTO shopManagerDTO = shopManagerMapper.getById(id);

        return shopManagerDTO;
    }

    /**
     * 发送短信验证码
     */
    @Override
    public Map<String, Object> sendVerifyCode(String phoneNumber) {
        /**根据mobilePhone查询商户管理员信息*/
        List<ShopManagerDTO> shopManagerDTOList = shopManagerMapper.getByMobilePhone(phoneNumber);
        if(shopManagerDTOList.size() == 0) {
            ExceptionUtil.businessException("用户不存在");
        }

        //  1、校验短信验证码模版是否正确
        //  查询短信模版
        String templateContent = ShortMsgUtil.querySmsTemplate("SMS_147915193");
        //  匹配${}
        Matcher matcher = Pattern.compile("\\$\\{[^\\{\\}]{1,}\\}").matcher(templateContent);
        List<String> templateVariables = new ArrayList<>();
        while(matcher.find()){
            templateVariables.add(matcher.group());
        }
        //  短信验证码模版变量错误，验证码模版有且只有一个变量
        if(templateVariables.size() != 1){
            ExceptionUtil.businessException("短信验证码模版变量错误，验证码模版有且只有一个变量");
        }

        //2、校验短信是否已经发送
        Map<String, Object> sendCodeMap = verifyCodeMap.get(phoneNumber);
        if(sendCodeMap != null && sendCodeMap.get("expire") != null){
            Date expire = (Date) sendCodeMap.get("expire");
            if(expire.getTime() > new Date().getTime()){
                ExceptionUtil.businessException("短信已经发送，请注意查收");
            }
        }

        //  3、发送短信
        Map<String, Object> paramMap = new HashMap<>();
        String verifyCode = String.valueOf((int)((Math.random()*9+1)*1000));
        if ("17692120322".equals(phoneNumber)) {
            verifyCode = "0000";
        }
//        String verifyCode = "0000";
        paramMap.put("code", verifyCode); //  验证码
        log.info("验证码：" + verifyCode);
        //  发送短信
        Map sendMap = ShortMsgUtil.sendVerifyCode("SMS_147915193", phoneNumber, paramMap);
//        Map sendMap = new HashMap();
//        sendMap.put("Code", "OK");
        if(sendMap.get("Code").equals("OK")){
            log.info("短信验证码发送成功");
            Date expire = DateTimeUtil.getCurrAfterSecondDate(new Date(), 30);
            Map<String, Object> codeMap = new HashMap();
            codeMap.put("code", verifyCode);
            codeMap.put("expire", expire);
            verifyCodeMap.put(phoneNumber, codeMap);

            return codeMap;
        } else {
            log.error("短信验证码发送失败");
            ExceptionUtil.businessException("短信验证码发送失败");
        }

        return null;
    }

    /**
     * 登录
     */
    @Override
    public AuthorizeVO login(LoginForm form) {
        Map<String, Object> codeMap = verifyCodeMap.get(form.getPhoneNumber());
        if(codeMap != null && form.getVerifyCode().equals(codeMap.get("code"))){
            Date expire = (Date) codeMap.get("expire");
            if(expire.getTime() < new Date().getTime()){
                ExceptionUtil.businessException("验证码已过期");
                return null;
            }
            //  清除验证码
            verifyCodeMap.remove(form.getPhoneNumber());
            //  清除其他失效验证码
            for(Map.Entry<String, Map> entry: verifyCodeMap.entrySet()){
                Map value = entry.getValue();
                Date expireOther = (Date) value.get("expire");
                if(expireOther.getTime() < new Date().getTime()){
                    verifyCodeMap.remove(entry.getKey());
                }
            }

            /**根据mobilePhone查询商户管理员信息*/
            List<ShopManagerDTO> shopManagerDTOList = shopManagerMapper.getByMobilePhone(form.getPhoneNumber());
            if(shopManagerDTOList.size() == 0) {
                ExceptionUtil.businessException("用户不存在");
                return null;
            }

            List<ManagerShopDTO> managerShopDTOList = managerShopMapper.getShopByManageId(shopManagerDTOList.get(0).getId());
            if (managerShopDTOList == null || managerShopDTOList.size() < 1){
                ExceptionUtil.businessException("没有店铺信息");
                return null;
            }

            LoginUser loginUser = new LoginUser();
            loginUser.setManagerId(shopManagerDTOList.get(0).getId());
            loginUser.setNickname(shopManagerDTOList.get(0).getUsername());
//            loginUser.setOpenid(shopManagerDTO.getOpenid());
            String token = JwtUtil.createJWT(loginUser);

            AuthorizeVO authorizeVO = new AuthorizeVO();
            authorizeVO.setToken(token);
            authorizeVO.setUserId(shopManagerDTOList.get(0).getId());
            authorizeVO.setUsername(shopManagerDTOList.get(0).getUsername());
            authorizeVO.setPhoneNumber(form.getPhoneNumber());
            return authorizeVO;
        } else {
            ExceptionUtil.businessException("验证码错误");
            return null;
        }
    }

    @Override
    public ShopManagerDTO authorize(WeiXinAuthorizeForm weiXinAuthorizeForm) {
        LoginUser loginUser = JwtUtil.getLoginUser(request);

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WeChatUtil.xcxAppId + "&secret=" + WeChatUtil.xcxAppSecret + "&js_code=" + weiXinAuthorizeForm.getCode() + "&grant_type=authorization_code";
        String response = HttpUtil.requestGet(url, null, null);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if(jsonObject.get("openid") == null){
            ExceptionUtil.businessException("openid为空");
        }
        //  获取openid
        String openid = jsonObject.get("openid").toString();
        //  获取session_key
        //String sessionKey = jsonObject.get("session_key").toString();

        ShopManagerDTO shopManagerDTO = shopManagerMapper.getById(loginUser.getManagerId());

        if(shopManagerDTO == null){
            ExceptionUtil.authorizeException("用户不存在");
        }
        shopManagerDTO.setOpenid(openid); //  openid
        shopManagerDTO.setAvatar(weiXinAuthorizeForm.getAvatar());   //  头像
        shopManagerDTO.setNickname(weiXinAuthorizeForm.getNickname());   //  昵称

        return shopManagerDTO;
    }

}
